﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using AntUnion.FrameWork.Model.Models;
using Microsoft.AspNetCore.Hosting;
using Util.Extension;
using AntUnion.FrameWork.Util;
using AntUnion.FrameWork.Model.BGModels;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class MenusController : BaseController
    {
        private readonly IWebHostEnvironment _hostingEnv;
        private readonly mtContext _context;

        public MenusController(mtContext context, IWebHostEnvironment hostingEnv) : base(context, hostingEnv)
        {
            _context = context;
            _hostingEnv = hostingEnv;
        }

        #region 菜单列表
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetListJson(int userType)
        {
            ListResult res = new ListResult();
            try
            {
                var data = await _context.TbMenus.Where(k => k.UserType == userType).OrderBy(k => k.Sort).ToListAsync();
                res.Code = 0;
                res.Count = _context.TbMenus.Count();
                res.Data = data;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        public IActionResult MenusTree(int roleid, int userType)
        {
            ViewBag.roleid = roleid;
            ViewBag.userType = userType;
            return View();
        }

        /// <summary>
        /// 获取tree菜单列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetTreeJson(int RoleId, int userType)
        {
            ListResult res = new ListResult();
            try
            {
                var data = await _context.TbMenus.Where(k => k.Pid == 0 && k.UserType == userType && k.State == 1).OrderBy(k => k.Sort).Select(n => new
                {
                    id = "M" + n.Id,
                    pid = n.Id,
                    type = 1,
                    title = n.Names,
                    Checked = _context.TbMenuRoles.Where(k => k.MenuId == n.Id && k.RoleId == RoleId && k.UserType == userType).Any(), //true,
                    spread = true,
                    children = _context.TbMenus.Where(k => k.Pid == n.Id && k.UserType == userType && k.State == 1).OrderBy(k => k.Sort).Select(x => new
                    {
                        id = "M" + x.Id,
                        pid = x.Id,
                        type = 1,
                        title = x.Names,
                        Checked = _context.TbMenuRoles.Where(k => k.MenuId == x.Id && k.RoleId == RoleId && k.UserType == userType).Any(),
                        spread = true,
                        children = _context.TbMenus.Where(k => k.Pid == x.Id && k.UserType == userType && k.State == 1).OrderBy(k => k.Sort).Select(y => new
                        {
                            id = "M" + y.Id,
                            pid = y.Id,
                            type = 1,
                            title = y.Names,
                            Checked = _context.TbMenuRoles.Where(k => k.MenuId == y.Id && k.RoleId == RoleId && k.UserType == userType).Any(),
                            spread = true,
                            //children = _context.TbPowers.Where(k => k.MenuId == y.Id).OrderBy(k => k.Sort).Select(p => new
                            //{
                            //    id = "P" + p.Id,
                            //    pid = p.Id,
                            //    type = 2,
                            //    title = p.Names,
                            //    spread = true,
                            //    Checked = _context.TbPowerRoles.Where(k => k.PowerId == p.Id && k.RoleId == RoleId).Any()
                            //}).ToList()
                        }).ToList()
                    }).ToList()
                }).ToListAsync();

                res.Code = 0;
                res.Count = _context.TbMenus.Count();
                res.Data = data;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 添加菜单
        public IActionResult Create(int pid, int userType)
        {
            TbMenu TbMenu = _context.TbMenus.FirstOrDefault(k => k.Id == pid && k.UserType == userType);
            if (TbMenu == null)
            {
                TbMenu = new TbMenu
                {
                    Pid = 0,
                    UserType = userType,
                    Names = "一级菜单"
                };
            }
            return View(TbMenu);
        }

        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Create(TbMenu model)
        {
            Result res = new Result();
            try
            {
                if (!TbMenuExists(model.Names, model.UserType, model.Pid.ToInt()))
                {
                    model.Creator = User.LoginName;
                    model.CreateDate = DateTimeUtil.Now;

                    _context.Add(model);
                    res.Code = 0;
                    res.Data = await _context.SaveChangesAsync();
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "菜单名称已存在";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 编辑菜单信息
        public async Task<IActionResult> Edit(int? id, int userType)
        {
            if (id == null)
            {
                return NotFound();
            }
            TbMenu TbMenu = await _context.TbMenus.FindAsync(id);
            if (TbMenu == null)
            {
                return NotFound();
            }
            else
            {
                TbMenu PTbMenu = await _context.TbMenus.FindAsync(TbMenu.Pid);
                if (PTbMenu != null)
                {
                    ViewBag.PNames = PTbMenu.Names;
                    List<TbMenu> PList = await _context.TbMenus.Where(k => k.Pid == 0 && k.UserType == userType).ToListAsync();
                    ViewBag.PList = PList;
                }
                else
                {
                    ViewBag.PNames = "一级菜单";
                    ViewBag.PList = null;
                }
            }
            return View(TbMenu);
        }
        /// <summary>
        /// 编辑菜单信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Edit(TbMenu item)
        {
            Result res = new Result();
            try
            {
                if (!TbMenuExists(item.Names, item.UserType, item.Pid.ToInt(), item.Id))
                {
                    TbMenu model = await _context.TbMenus.FindAsync(item.Id);
                    if (model != null)
                    {
                        model.UserType = item.UserType;
                        model.Names = item.Names;
                        model.Pid = item.Pid;
                        model.Url = item.Url;
                        model.Image = item.Image;
                        model.Sort = item.Sort;
                        model.State = item.State;
                        model.Remark = item.Remark;

                        res.Code = 0;
                        res.Data = await _context.SaveChangesAsync();
                    }
                    else
                    {
                        res.Code = 1;
                        res.Msg = "菜单不存在";
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "菜单名称已存在";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UpdateState(int id, int intState)
        {
            ListResult res = new ListResult();
            try
            {
                TbMenu TbMenu = await _context.TbMenus.FindAsync(id);

                TbMenu.State = intState;
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 删除菜单
        /// <summary>
        /// 删除单个菜单
        /// </summary>
        /// <param name="id">菜单ID</param>
        /// <returns></returns>
        [HttpPost, ActionName("Delete")]
        public async Task<JsonResult> Delete(int id)
        {
            Result res = new Result();
            try
            {
                TbMenu TbMenu = await _context.TbMenus.FindAsync(id);

                _context.TbMenus.Remove(TbMenu);
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids">要删除的菜单ID；多个用“,”分开</param>
        /// <returns></returns>
        [HttpPost, ActionName("DeleteItems")]
        public async Task<IActionResult> DeleteItems(string ids)
        {
            Result res = new Result();
            try
            {
                List<int> list = new List<int>();
                string[] idList = ids.Split(',');
                foreach (string id in idList)
                {
                    list.Add(id.ToInt());
                }
                List<TbMenu> userList = await _context.TbMenus.Where(k => list.Contains(k.Id)).ToListAsync();
                foreach (TbMenu model in userList)
                {
                    _context.TbMenus.Remove(model);
                }
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 判断是否存在
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="Name">菜单名称称</param>
        /// <param name="id">排除ID</param>
        /// <returns></returns>
        private bool TbMenuExists(string Name, int userType, int pid = 0, int id = 0)
        {
            if (id == 0)
                return _context.TbMenus.Any(e => e.Names == Name && e.UserType == userType && e.Pid == pid);
            else
                return _context.TbMenus.Any(e => e.Id != id && e.Names == Name && e.UserType == userType && e.Pid == pid);
        }
        #endregion

        /// <summary>
        /// 设置权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> SavePower(int RoleId, int userType, List<TopMenuModel> list)
        {
            Result res = new Result();
            try
            {
                if (list != null)
                {
                    _context.Database.ExecuteSqlRaw($"DELETE FROM tb_menu_role WHERE role_id={RoleId}");
                    _context.Database.ExecuteSqlRaw($"DELETE FROM tb_power_role WHERE role_id={RoleId}");
                    TbMenuRole menuRole = null;
                    foreach (TopMenuModel item in list)
                    {
                        menuRole = new TbMenuRole
                        {
                            RoleId = RoleId,
                            MenuId = item.pid,
                            UserType = userType
                        };
                        _context.Add(menuRole);
                        if (item.children != null)
                        {
                            foreach (TowMenuModel items in item.children)
                            {
                                menuRole = new TbMenuRole
                                {
                                    RoleId = RoleId,
                                    MenuId = items.pid,
                                    UserType = userType
                                };
                                _context.Add(menuRole);
                                if (items.children == null)
                                {
                                    continue;
                                }
                                foreach (ThreeMenuModel threeItems in items.children)
                                {
                                    menuRole = new TbMenuRole
                                    {
                                        RoleId = RoleId,
                                        MenuId = threeItems.pid,
                                        UserType = userType
                                    };
                                    _context.Add(menuRole);
                                }
                            }
                        }
                    }

                    res.Code = 0;
                    res.Data = await _context.SaveChangesAsync();
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
    }
}